import { getGraph,
  addGraph,
  delGraph,
  fixGraphStatus,
  downloadGraph,
  fetchGraphCategory,
  doEditCategory
} from '@/services/knowledgegraph';
import { routerRedux } from 'dva/router';

export default {
  namespace: 'knowledgeGraphList',
  state: {
    total: null,
    data: [],
    loading: false,
  },

  effects: {
    *fetchList({ payload, callback }, { call, put }) {
      const response = yield call(getGraph, payload);
      if (callback && typeof callback === 'function') {
        callback(response);
      }
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *addGraph({ payload, callback }, { call, put }) {
      const response = yield call(addGraph, payload);
      if (callback && typeof callback === 'function') {
        callback(response);
      }
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *delGraph({ payload, callback }, { call, put }) {
      const response = yield call(delGraph, payload);
      if (callback && typeof callback === 'function') {
        callback(response);
      }
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *fixGraphStatus({ payload, callback }, { call, put }) {
      const response = yield call(fixGraphStatus, payload);
      if (callback && typeof callback === 'function') {
        callback(response);
      }
      yield put({
        type: 'save',
        payload: response,
      });
    },
    * redirect({ payload, callback }, { call, put }) {
      yield put(
        routerRedux.push({
          pathname: '/knowledgeGraph/edit',
          query: payload,
        }),
      );
    },
    * get({ payload, callback }, { call, put }) {
      const response = yield call(downloadGraph, payload);
      if (callback && typeof callback === 'function') {
        callback(response);
      }
      yield put({
        type: 'save',
        payload: response,
      });
    },
    * getGraphCategory({ payload, callback }, { call, put }) {
      const response = yield call(fetchGraphCategory, payload);
      if (callback && typeof callback === 'function') {
        callback(response);
      }
      yield put({
        type: 'save',
        payload: response,
      });
    },
    * editCategory({ payload, callback }, { call, put }) {
      const response = yield call(doEditCategory, payload);
      if (callback && typeof callback === 'function') {
        callback(response);
      }
      yield put({
        type: 'save',
        payload: response,
      });
    },
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
